/**
 * Copyright HCP Technology 
 * www.hcp.vn
 */
package controllers;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;

import models.ContentModel;
import notifiers.Mails;
import play.Logger;
import play.cache.Cache;
import play.data.Upload;
import play.data.validation.Required;
import util.PaginationInfo;
import util.SimpleCache;
import util.Util;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.FinalizationException;
import com.google.appengine.api.files.LockException;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;

public class Content extends Application {
	
	
	public static void index(){
		Logger.info("----render template index-----");
		if(Application.getUser() != null){
			render();	
		}else{
			Application.login();
		}
		
	}
	
	public static void create(@Required Upload data, @Required String title, @Required String description, @Required String category, @Required boolean invisible){
		Logger.info("invisible >>>" + invisible);
		if(data == null) {
			String alias = Util.convertUTF8TOASCII(title);
			ContentModel content = new ContentModel("", category, Application.getUser(), title, alias, description, false, invisible, request.remoteAddress);
			content.insert();
			SimpleCache.set("content_" + content.id, content);
			Mails.sendContent(content);
			showContent(content.id, alias);
		}
		
		if(data != null && data.getContentType().compareTo("image/jpg") != 0 && data.getContentType().compareTo("image/jpeg") != 0 && data.getContentType().compareTo("image/gif") != 0 && data.getContentType().compareTo("image/png") != 0  ) {
			index();
		}
		if(Application.getUser() != null){
			if(validation.hasErrors()){
				Logger.info("display error");
				flash.error("Oops, please input field required");
				index();
			}
			  FileService fileService = FileServiceFactory.getFileService();
			  AppEngineFile file;
			try {
				file = fileService.createNewBlobFile(data.getContentType(), data.getFileName());
				// Open a channel to write to it
				boolean lock = true;
				FileWriteChannel writeChannel = fileService.openWriteChannel(
						file, lock);
				writeChannel.write(ByteBuffer.wrap(data.asBytes()));
				writeChannel.closeFinally();
				BlobKey key = fileService.getBlobKey(file);
				String alias = Util.convertUTF8TOASCII(title);
				ContentModel content = new ContentModel(key.getKeyString(), category, Application.getUser(), title, alias, description, true, invisible, request.remoteAddress);
				content.update();
				content.insert();
				SimpleCache.set("content_" + content.id, content);
				Mails.sendContent(content);
				
				showContent(content.id, alias);
				
			} catch (FileNotFoundException e) {
				Logger.info(e.getMessage());
			} catch (FinalizationException e) {
				Logger.info(e.getMessage());
			} catch (LockException e) {
				Logger.info(e.getMessage());
			} catch (IOException e) {
				Logger.info(e.getMessage());
			}
		}
		index();
	}
	
	public static void showContent(Long id, String alias){
		ContentModel content = (ContentModel)SimpleCache.getContent(id, alias, getUser());
		if(content == null || !content.alias.equals(alias)){
			renderTemplate(Util.ERROR_404);
		}
		String dataFilterContent = "";
		String description = "";
		if(!content.active){
			dataFilterContent = Util.filterContent(content);
			System.out.println(">>>>>>>>>.Data is filter" + dataFilterContent);
			if(!dataFilterContent.isEmpty()){
				Util.replaceContent(content, dataFilterContent);
			}
		}
		render(content, dataFilterContent, description);
	}
	
	
	public static void showPicture(String path){
		BlobKey key = new BlobKey(path);
		BlobInfoFactory factory = new BlobInfoFactory();
		BlobInfo info = factory.loadBlobInfo(key);
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
        Image oldImage = ImagesServiceFactory.makeImageFromBlob(key);
        response.cacheFor("48h");
        response.setContentTypeIfNotSet(info.getContentType());
		renderBinary(new ByteArrayInputStream(Util.scaleImage(imagesService, oldImage)));
			
	}
	
	public static void deleteContent(Long id){
		ContentModel content = (ContentModel)Cache.get("content_" + id);
		if( content == null){
			Logger.info("-------dont find info in Cache-----");
			content = ContentModel.findById(id);
		}
		if(getUser().equals(content.user)){
			Logger.info("------delete content id-----" + id);
			String category = content.category;
			ContentModel.deleteContent(id);
			Cache.delete("content_" + id);
			List<ContentModel> listContentModels = ContentModel.findByCategory(content.category, true);
			Cache.delete("category_" + category);
			Cache.set("category_" + category, listContentModels);
			renderText(Util.SUCCESS);	
		}
		renderText(Util.FAIL);
	}
	
	public static List<models.CommentModel> listComments(Long id){
		return models.ContentModel.listComments(id);
	}
	
	public static void showAllContent(){
		List<ContentModel> listContentModels = Cache.get("contents", List.class);
		if(listContentModels == null){
			listContentModels = ContentModel.listNewContent(true, 0);
			if(listContentModels != null){
				Cache.set("contents", listContentModels);
			}
		}
		render(listContentModels);
	}
	

	/*show all content write by user*/
	public static void managerContent(){
		if(getUser() != null){
			List<ContentModel> contentModels = ContentModel.findByUser(getUser());
			PaginationInfo paginationInfo = new PaginationInfo();
			render(contentModels, paginationInfo);	
		}
	}
	/*edit content*/
	public static void editContent(Long id, String alias){
		ContentModel content = (ContentModel)SimpleCache.getContent(id, alias, getUser());
		if(content == null){
			content = ContentModel.findById(id);
		}
		if(content == null || !content.alias.equals(alias)){
			Logger.info("--return page 404-->>"  + Util.ERROR_404);
			renderTemplate(Util.ERROR_404);
		}
//		String desc = content.description.replaceAll("\r\n", "");
		render(content);
	}
	
	/*update content*/
	public static void update(@Required Long id, @Required String title, @Required String description, @Required String category, @Required boolean invisible){
		if(Application.getUser() != null){
			Logger.info(" id >>" + id);
			Logger.info(" title >>" + title);
			Logger.info(" desc >>" + description);
			Logger.info(" cate >>" + category);
			ContentModel content = SimpleCache.getContent(id);
			if(content == null){
				content = ContentModel.findById(id);
			}
			content.category = category;
			content.description = description;
			content.title = title;
			content.alias = Util.convertUTF8TOASCII(title);
			content.ip = request.remoteAddress;
			content.invisible = invisible;
			content.updateStatus();
			content.update();
			showContent(content.id, content.alias);
		}
		index();
	}
}
